﻿using ProgressTracker.Domain;
using ProgressTracker.Domain.Contracts;
using ProgressTracker.Domain.Messages;
using ProgressTracker.WebUI.Models.Progress;
using ProgressTracker.WebUI.Translation;
using System;
using System.Web.Mvc;

namespace ProgressTracker.WebUI.Controllers
{
    [Authorize]
    public class ProgressController : Controller
    {
        private IDayService _dayService;
        private IDayModelMapper _dayMapper;

        public ProgressController(
            IDayService dayService, 
            IDayModelMapper dayMapper)
        {
            _dayService = dayService;
            _dayMapper = dayMapper;
        }

        public ActionResult Day(DateTime? day)
        {
            var dateToUse = day.HasValue ? day.Value.Date : DateTime.Today;

            Day dayRequested  = _dayService.GetDay(dateToUse, User.Identity.Name);

            return View(new DayViewModel
                {
                    Day = _dayMapper.Create(dayRequested)
                });
        }



        public PartialViewResult DayTable(DateTime? day)
        {
            var dateToUse = day.HasValue ? day.Value.Date : DateTime.Today;

            Day dayRequested = _dayService.GetDay(dateToUse, User.Identity.Name);

            return PartialView("_DayTable", _dayMapper.Create(dayRequested));
        }

        [HttpPost]
        public JsonResult Update(UpdateDayModel model)
        {
            //update day itself
            _dayService.UpdateDay(new UpdateDayRequest
            {
                Date = model.Date,
                Notes = model.Notes,
                UserEmail = User.Identity.Name
            });

            foreach(var taskModel in model.TasksToUpdate)
            {
                //mark tasks as complete
                var request = new UpdateTaskCompletenessRequest
                {
                    Date = model.Date,
                    UserEmail = User.Identity.Name,
                    IsComplete = taskModel.Complete,
                    TaskId = taskModel.Id
                };

                _dayService.UpdateTaskCompleteness(request);
            }

            var result = new UpdateResultModel
            {
                Success = true,
                Message = "Successfully updated tasks!"
            };
            
            return Json(result);
        }
	}
}